package com.ks.pc.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.session.RowBounds;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import com.google.common.base.Function;
import com.google.common.collect.Ordering;
import com.ks.dto.BrandDto;
import com.ks.dto.ClassifyDto;
import com.ks.dto.ImgDto;
import com.ks.dto.PaginationDto;
import com.ks.dto.Product2Dto;
import com.ks.dto.ProductDto;
import com.ks.pc.dao.DaoSupport;
import com.ks.pc.service.CommonService;

import net.chinahrd.utils.CollectionKit;

@Service("commonService")
public class CommonServiceImpl implements CommonService {

	public static final Logger logger = Logger.getLogger(SysProductServiceImpl.class);

	@Autowired
	private DaoSupport daoSupport;
	@Autowired
	private HttpServletRequest request;

	@Override
	public List<ClassifyDto> queryClassifyAll() {
		try {
			return daoSupport.findForList("CommonMapper.queryClassifyByCondition", null);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return CollectionKit.newList();
	}

	@Override
	public List<ClassifyDto> queryClassifyBySearchTxt(Map<String, Object> param) {
		// if (null == searchTxt || null == rowBounds) {
		// logger.info(DictEnum.IS_NULL.getDesc());
		// return CollectionKit.newList();
		// }
		try {
			return daoSupport.findForList("CommonMapper.queryClassifyByCondition", param);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return CollectionKit.newList();
	}

	 @Override
	public PaginationDto<ClassifyDto> queryClassifyByCondition(Integer page, Integer rows, String searchTxt) {
		PaginationDto<ClassifyDto> pageDto = new PaginationDto<ClassifyDto>(page, rows);
		Map<String, Object> wrapParams = this.wrapParams(null, pageDto.getOffset(), pageDto.getLimit(), searchTxt);
		List<ClassifyDto> dtos;
		try {
			Integer count = daoSupport.findForObject("CommonMapper.findClassifyByConditionCount", wrapParams);
			dtos = daoSupport.findForList("CommonMapper.queryClassifyByCondition", wrapParams);
			pageDto.setRecords(count);
			pageDto.setRows(dtos);
		} catch (Exception e) {
			logger.debug(e.getMessage());
		}
		return pageDto;
	}

	@Override
	public List<Product2Dto> queryProductAll() {
		try {
			return daoSupport.findForList("CommonMapper.queryProductAll", null);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return CollectionKit.newList();
	}

	@Override
	public List<BrandDto> queryBrandAllByClassifyId(Integer classifyId) {
		PaginationDto<BrandDto> rs = this.queryBrandByCondition(classifyId, 9999, 9999, null);
		if (rs.getRows().size() > 0) {
			return rs.getRows();
		}
		return CollectionKit.newList();
	}

	/**
	 * 组装参数：</br>
	 * 1分类ID</br>
	 * 2分页对象给limit用</br>
	 * 3模糊查询key</br>
	 * 
	 * @param classifyId
	 *            分类ID
	 * @param page
	 *            页号
	 * @param rows
	 *            每页多少行
	 * @param searchTxt
	 *            模糊条件
	 * @return
	 */
	private Map<String, Object> wrapParams(Integer classifyId, Integer offset, Integer limit, String searchTxt) {
		Map<String, Object> param = new HashMap<String, Object>();
		if (null != offset && null != limit) {
			RowBounds rowBounds = new RowBounds(offset, limit);
			param.put("rowBounds", rowBounds);
		}
		if (null != searchTxt) {
			param.put("searchTxt", searchTxt);
		}
		if (null != classifyId) {
			param.put("classifyId", classifyId);
		}
		return param;
	}

	@Override
	public PaginationDto<BrandDto> queryBrandByCondition(Integer classifyId, Integer page, Integer rows,
			String searchTxt) {
		PaginationDto<BrandDto> pageDto = new PaginationDto<BrandDto>(page, rows);
		Map<String, Object> wrapParams = this.wrapParams(classifyId, pageDto.getOffset(), pageDto.getLimit(),
				searchTxt);
		List<BrandDto> dtos;
		try {
			Integer count = daoSupport.findForObject("CommonMapper.findBrandByConditionCount", wrapParams);
			dtos = daoSupport.findForList("CommonMapper.queryBrandByCondition", wrapParams);
			pageDto.setRecords(count);
			pageDto.setRows(dtos);
		} catch (Exception e) {
			logger.debug(e.getMessage());
		}
		return pageDto;
	}

	@Override
	public List<Product2Dto> queryProductAllByBrandId(Integer brandId) {
		try {
			return daoSupport.findForList("CommonMapper.queryProductAllByBrandId", brandId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return CollectionKit.newList();
	}

	@Override
	public List<Product2Dto> queryProductBySearchTxt(Map<String, Object> param) {
		try {
			return daoSupport.findForList("CommonMapper.queryProductBySearchTxt", param);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return CollectionKit.newList();
	}

	@Override
	public List<Product2Dto> queryProductAllByClassifyId(Integer classifyId, List<Product2Dto> dtos) {
		List<Product2Dto> rs = CollectionKit.newList();
		if (null == classifyId)
			return rs;
		for (Product2Dto dto : dtos) {
			if (dto.getClassifyId() == classifyId) {
				rs.add(dto);
			}
		}
		return compOnResultOfTest(rs);
	}

	/**
	 * 倒序-按showIndex
	 * 
	 * @param dtos
	 * @return
	 */
	private List<Product2Dto> compOnResultOfTest(List<Product2Dto> dtos) {
		Ordering<Product2Dto> ordering = Ordering.natural().nullsFirst().reverse()
				.onResultOf(new Function<Product2Dto, Integer>() {
					public Integer apply(Product2Dto dto) {
						return dto.getShowIndex();
					}
				});
		return ordering.immutableSortedCopy(dtos);
	}

	@Override
	public List<Product2Dto> queryProductAllByClassifyId(Integer classifyId) {
		List<Product2Dto> productRs = this.queryProductAll();
		List<Product2Dto> rs = CollectionKit.newList();
		if (null != classifyId) {
			rs = this.queryProductAllByClassifyId(classifyId, productRs);
			return rs;
		} else {
			return productRs;
		}
	}

	@Override
	public ProductDto findProductById(Integer productId) {
		try {
			return daoSupport.findForObject("CommonMapper.findProductById", productId);
		} catch (Exception e) {
			logger.debug(e.getMessage());
		}
		return null;
	}

	@Override
	public boolean insertImgDto(ImgDto dto) {
		try {
			daoSupport.save("CommonMapper.insertImgDto", dto);
			return true;
		} catch (Exception e) {
			logger.debug(e.getMessage());
		}
		return false;
	}

	public void checkSessionTimeout() {
		HttpSession session = request.getSession();
		Boolean activate = (Boolean) session.getAttribute("activate");
		System.out.println("=================" + activate);
		if (null == activate || false == activate) {
			// sysController.logout();
		}
	}

	@Override
	public Map<Integer, List<Product2Dto>> groupByShowIndexClassify(List<Product2Dto> list) {
		Map<Integer, List<Product2Dto>> rs = CollectionKit.newMap();
		if (null == list) {
			return rs;
		}
		MultiValueMap<Integer, Product2Dto> map = new LinkedMultiValueMap<Integer, Product2Dto>();
		for (Product2Dto dto : list) {
			if (null != dto.getShowIndexClassify()) {
				map.add(dto.getShowIndexClassify(), dto);
			}
		}
		for (Entry<Integer, List<Product2Dto>> entry : map.entrySet()) {
			rs.put(entry.getKey(), entry.getValue());
		}
		return rs;
	}

}
